import { createRouter, createWebHashHistory } from 'vue-router'
import Login from '../views/Login.vue'
import MainBox from '../views/MainBox.vue'
import RoutesConfig from './config'
import  store from '../store/index'

const routes = [
  {
    path: "/login",
    name: "login",
    component: Login
  },
  {
    path: "/mainbox",
    name: "mainbox",
    component: MainBox
  }
]
// mainBox 的嵌套路由，后面根据权限动态添加
const router = createRouter({
  history: createWebHashHistory(),
  routes
})
// 路由拦截：每次路由跳转之前都会执行次函数
router.beforeEach((to,from,next)=>{
  // console.log("to.name:",to)
  if (to.name ==='login'){
    next()
  }else {
    // 如果已经登陆过了，next（）
    // 未登陆过：重定向 login
    if (!localStorage.getItem("token")){
      next({
        path: "/login",
      })
    }else {
      if (!store.state.isGetterRouter){
        ConfigRouter();
        next({
          path: to.fullPath
        })
      }else {
        next();
      }
    }
  }
})

const ConfigRouter = () =>{

  RoutesConfig.forEach(item =>{
    router.addRoute("mainbox",item)
    // console.log("router.addRoute();函数执行22")
  })

  //改变是否第一次进来的参数
  store.commit("changeGetterRouter",true)
}


export default router
